<template>
  <div>
    <el-dialog v-model="state.showDialog" destroy-on-close :title="title" draggable :close-on-click-modal="false"
      :close-on-press-escape="false" width="569px">
      <el-form ref="formRef" :model="form" size="default" label-width="80px">
        <el-row :gutter="35">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="工站代号" :rules="[{ required: true, message: '请选中工站代号', trigger: ['blur', 'change'] }]">
              <el-select v-model="form.stationId" placeholder="请选中工站代号">
                <el-option v-for="item in state.stationTreeData" :key="item.id" :label="item.stationCode"
                  :value="item.id">
                  <span style="float: left">{{ item.stationCode }}</span>
                  <span style="
                              float: right;
                              color: var(--el-text-color-secondary);
                              font-size: 13px;">
                    {{ item.stationName }}
                  </span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="验证次数" prop="verifyCount"
              :rules="[{ required: true, message: '请输入最大验证次数', trigger: ['blur', 'change'] }]">
              <el-input-number v-model="form.verifyCount" autocomplete="off" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="工站类型" prop="stationRole"
              :rules="[{ required: true, message: '请选择工站类型', trigger: ['blur', 'change'] }]">
              <el-select v-model="form.stationRole" placeholder="请选择工站类型" class="w100">
                <el-option v-for="item in porpuseOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="理论节拍" prop="theoreticalBeat"
              :rules="[{ required: false, message: '理论节拍', trigger: ['blur', 'change'] }]">
              <el-input-number v-model="form.theoreticalBeat" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="排序" prop="sort"
              :rules="[{ required: false, message: '排序', trigger: ['blur', 'change'] }]">
              <el-input-number v-model="form.sort" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="校验规则" :rules="[{ required: true, message: '请输入校验规则', trigger: ['blur', 'change'] }]">
              <template #label>
                <div class="my-flex-y-center">
                  工站<el-tooltip effect="dark" placement="top" :hide-after=0>
                    <template #content>选择校验的工站</template>
                    <SvgIcon name="ele-InfoFilled" class="ml5" />
                  </el-tooltip>
                </div>
              </template>
              <el-tree-select v-model="internalVerifyRule" :data="state.stationTreeData" node-key="id"
                :props="{ label: 'stationCode' }" render-after-expand fit-input-width clearable filterable multiple
                collapse-tags collapse-tags-tooltip class="w100" :default-expanded-keys="state.expandRowKeys">
                <template #default="{ data }">
                  <span class="my-flex my-flex-between">
                    <span>{{ data.stationCode }}</span>
                    <span class="my-line-1 my-mlr-12" :title="data.stationName">
                      {{ data.stationName }}
                    </span>
                  </span>
                </template>
              </el-tree-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onCancel" size="default">取 消</el-button>
          <el-button type="primary" @click="onSure" size="default" :loading="state.sureLoading">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts" name="industry/route-detail/form">
import { reactive, toRefs, getCurrentInstance, ref, watch, computed } from 'vue'
import { RouteDetailGetListOutput, RouteDetailAddInput, RouteDetailUpdateInput, WorkStationGetListOutput } from '/@/api/industry/data-contracts'
import { listToTree } from '/@/utils/tree'

import { RouteDetailApi } from '/@/api/industry/RouteDetail'
import { WorkStationApi } from '/@/api/industry/WorkStation'


import eventBus from '/@/utils/mitt'

defineProps({
  title: {
    type: String,
    default: '',
  },
})
const { proxy } = getCurrentInstance() as any
const formRef = ref()
const state = reactive({
  showDialog: false,
  sureLoading: false,
  expandRowKeys: [] as Number[],
  routeDetailData: [] as RouteDetailGetListOutput[],
  stationTreeData: [] as WorkStationGetListOutput[],
  form: {} as RouteDetailAddInput & RouteDetailUpdateInput,
  contiAdd: false,

})
const { form } = toRefs(state)

const porpuseOptions = [
  { id: 0, name: '上线' },
  { id: 1, name: '加工' },
  { id: 2, name: '下线' },
  { id: 3, name: '返修' }
]

// 转换函数
const parseStringToIds = (str: any) => {
  try {
    return JSON.parse(str) || [];
  } catch (e) {
    console.error('解析工站代号失败:', e);
    return [];
  }
};

const convertIdsToString = (ids: number[]) => {
  return JSON.stringify(ids);
};

// 双向绑定处理
const internalVerifyRule = computed({
  get: () => parseStringToIds(form.value.verifyRule),
  set: (newValue) => {
    form.value.verifyRule = convertIdsToString(newValue);
  }
});
watch(internalVerifyRule, (newIds) => {
  state.expandRowKeys = [...new Set([...state.expandRowKeys, ...newIds])];
}, { immediate: true });
// 打开对话框
const open = async (row: any = {}) => {
  state.contiAdd = false
  await getStations()
  if (row.id > 0) {
    const res = await new RouteDetailApi().get({ id: row.id }, { loading: true }).catch(() => {
      proxy.$modal.closeLoading()
    })
    if (res?.success) {
      state.form = res.data as RouteDetailAddInput & RouteDetailUpdateInput
    }
  } else {
    state.form = { productRouteId: row.productRouteId } as RouteDetailAddInput & RouteDetailUpdateInput
  }
  state.showDialog = true
}
// 确定
const onSure = () => {
  formRef.value.validate(async (valid: boolean) => {
    if (!valid) return

    state.sureLoading = true
    let res = {} as any
    if (state.form.id != undefined && state.form.id > 0) {
      res = await new RouteDetailApi().update(state.form, { showSuccessMessage: true }).catch(() => {
        state.sureLoading = false
      })
    } else {
      res = await new RouteDetailApi().add(state.form, { showSuccessMessage: true }).catch(() => {
        state.sureLoading = false
      })
    }
    state.sureLoading = false

    if (res?.success) {
      if (state.contiAdd) {
        formRef.value!.resetFields()
      }
      eventBus.emit('refreshRouteDetail')
      state.showDialog = state.contiAdd
    }
  })
}

// 取消
const onCancel = () => {
  state.showDialog = false
}

const getStations = async () => {
  const res = await new WorkStationApi().getList({})
  if (res?.success && res.data && res.data.length > 0) {
    state.stationTreeData = listToTree(res.data) as WorkStationGetListOutput[]
  } else {
    state.stationTreeData = []
  }
}

defineExpose({
  open,
})
</script>